/* eslint-disable */
/**
 * Created by GYL on 2018/8/24
 */
//事件模板管理
import React, { Component } from 'react';
import Filtrate from '../../../components/common/Filtrate';
import Container from "../../../components/common/Container";
import MyTable from "../../../components/common/MyTable";
import PublicService from "../../../services/PublicService";
import MyModal from '../../../components/common/MyModal';
import request from '../../../utils/request';
import MyPagination from "../../../components/common/MyPagination";
import { Tabs, Form, Row, Tooltip, Input, Select, DatePicker, TreeSelect, Drawer, Radio, notification, Button, Statistic, Col, Divider, Spin } from 'antd';
import moment from 'moment';
import config from '../../../config';
import Util from '../../../utils/Util';
import Tab4_sub from '../sub/Tab4_sub';
import '../../../config';
import SubeventsInfo from '../sub/SubeventsInfo';
const { TextArea } = Input;
const FormItem = Form.Item;
var treeArr = []
class Tab4 extends Component {

  state = {
    spinning: false,
    TaskArr: [],
    selectArr: [],
    SubTaskVisible: false,
    params: {},
    pageSize: 10,
    pageIndex: 1,
    total: 0,
    delConfirm: false,
    addModal: false,
    selectedRowKeys: [],
    dataSate: [],
    taskId: '',
    addWrap: false,
    editWrap: false,
    EditArr: [],
    AddArr: [],
    MyModal1Visible: false,
    visible: false,
    arr: [],
    haveRead: false,
    ccType: '',
    copyId: '',
    sjmc:[],
    fqr:[]
  }
  componentDidMount() {
    // this.onNotification(1)
    this.onSubmit(1, 10)
    global.constants.name.onmessage = (event) => {
      const data = JSON.parse(event.data)
      // console.log(data)
      if (data.ret.type == 2) {
        this.onNotification(data)
      }
    }
    this.dropDownBoxFour();

  }

  dropDownBoxFour = () => {
    request({
      url: '/pm-web/projectmanage/findData/dropDownBoxFour',
      method: 'GET',
      params: {
        userId: PublicService.getCookie('userId'),
        num: 4
      }
    }).then(data => {
      if (data.rc === 0) {
        this.setState({
          sjmc: data.ret.sjmc,
          fqr: data.ret.fqr
        })
      }

    })
  }

  onNotification = (data) => {
    let flag = true
    const key = `open${Date.now()}`;
    const btn = (
      <div>
        <Button size="small" onClick={() => {
          notification.close(key)
          flag = false
        }}>
          暂不刷新
        </Button>
        <Divider type="vertical" />
        <Button type="primary" size="small" onClick={() => {
          notification.close(key)
          this.onSubmit(1, 10)
        }
        }>
          立即刷新
        </Button>
      </div>
    );
    const { Countdown } = Statistic;
    const deadline = Date.now() + 1000 * 5; // Moment is also OK
    const CountdownBox =
      (
        <Countdown title="刷新倒计时" value={deadline} format=" s 秒" />
      )



    notification.open({
      message: '接收到新的抄送消息,即将自动刷新页面',
      description:
        CountdownBox,
      btn,
      key,
      onClose: close,
    });

    setTimeout(() => {
      if (flag) {
        this.onSubmit(1, 10)
        notification.close(key)
      }

    }, 5000)


  }
  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
    this.onSubmit(1, 10)

  };


  //查询
  onSubmit = (page, size) => {
    const params = this.f1.getForm().getFieldsValue();
    params.page = page;
    params.rows = size;
    if (params.time.length > 0) {
      params.startTime = moment(params.time[0]).format('YYYY-MM-DD HH:mm:ss');
      params.endTime = moment(params.time[1]).format('YYYY-MM-DD HH:mm:ss');
    } else {
      params.startTime = '';
      params.endTime = '';
    }
    params.haveRead = this.state.haveRead ? 0 : ''
    // params.startTime=params.eventBasicName12[0]?moment(params.eventBasicName12[0]).format("YYYY-MM-DD HH:mm:ss"):'';
    // params.endTime=params.eventBasicName12[1]?moment(params.eventBasicName12[1]).format("YYYY-MM-DD HH:mm:ss"):'';
    params.userId = PublicService.getCookie('userId');
    this.setState({
      params,
      spinning: true,
      pageIndex:page,
      pageSize:size
    })
    // console.log(params)

    request({
      url: '/pm-web/process/task/getCcMe',
      method: 'POST',
      data: params
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {

        data.ret.items.forEach((item) => {
          // item.eventBasicStage = item.eventBasicStage == 1 ? '项目前期' : item.eventBasicStage == 2 ? '项目实施' : item.eventBasicStage == 3 ? '项目验收' : '项目结算'
          // item.lastChangeTime = moment(item.lastChangeTime).format("YYYY-MM-DD HH:mm:ss")
          // item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss")
        })

        this.setState({
          dataSate: data.ret.items,
          total: data.ret.rowCount,
          spinning: false
        })
      }
    })
  }

  //重置
  ResetForm = () => {
    console.log('重置')
    this.setState({
      pageIndex:1,
      pageSize:10
    },() => {
      this.onSubmit(1,10)
    })
  }





  // 分页
  onChangePage = (page, size) => {
    this.setTimeAndSearch(this.state.params, page, size);
    this.setState({
      pageSize: size,
      pageIndex: page,
    })
  };

  onChangePage1 = (page, size) => {

    this.setTimeAndSearch(this.state.params, 1, size);
    this.setState({
      pageSize: size,
      pageIndex: 1,
    })
  };

  setTimeAndSearch = (val, pageIndex, row) => {

    this.setState({
      spinning: true
    })

    // console.log(val, pageIndex, row)
    val.page = pageIndex;
    val.rows = row;

    val.haveRead = this.state.haveRead ? 0 : ''
    // params.startTime=params.eventBasicName12[0]?moment(params.eventBasicName12[0]).format("YYYY-MM-DD HH:mm:ss"):'';
    // params.endTime=params.eventBasicName12[1]?moment(params.eventBasicName12[1]).format("YYYY-MM-DD HH:mm:ss"):'';
    val.userId = PublicService.getCookie('userId');

    request({
      url: '/pm-web/process/task/getCcMe',
      method: 'POST',
      data: val
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {

        data.ret.items.forEach((item) => {
          // item.eventBasicStage = item.eventBasicStage == 1 ? '项目前期' : item.eventBasicStage == 2 ? '项目实施' : item.eventBasicStage == 3 ? '项目验收' : '项目结算'
          // item.lastChangeTime = moment(item.lastChangeTime).format("YYYY-MM-DD HH:mm:ss")
          // item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss")
        })

        this.setState({
          dataSate: data.ret.items,
          total: data.ret.rowCount,
          spinning: false
        })
      }
    })
  };
  //查看
  onCheck = (record) => {
    // console.log(record)
    if (record.haveRead != 1) {
      //修改抄送为已读
      request({
        url: '/pm-web/process/task/updateHaveRead',
        method: 'POST',
        data: { id: record.id, userId: PublicService.getCookie('userId') }
      }).then(data => {

      })
    }


    if (record.ccType === 3) {
      request({
        url: '/pm-web/process/task/getCopiedChildEvents',
        method: 'POST',
        data: { copyId: record.copyId }
      }).then(data => {
        if (data.rc === 0) {
          this.setState({
            SubeventsInfoData: data.ret.svh,
            SubeventsInfoVisible: true
          })
         
        }
      })
    } else {
      this.setState({
        ccType: record.ccType,
        taskId: record.taskId
      })
      setTimeout(() => {
        this.showDrawer()
      }, 500)
    }



  }

  //保存按钮事件
  onModalSave = () => {



  }

  // 取消保存
  ModalCancel = (type) => {
    let t = this;
    t.setState({
      [type]: false,
      modalBtnLoading: false
    })
    this.onSubmit( this.state.pageIndex, this.state.pageSize);

  };

  onHaveRead = () => {
    this.setState({
      haveRead: !this.state.haveRead
    })
  }


  render() {
    let t = this
    let width = document.body.clientWidth;
    const height = document.body.clientHeight;
    let containerHeight = '71vh';
    let tableHeight = 320;
    let autoCompleteWidth = 340
    if (width > 1367) {
      tableHeight = 340;
      containerHeight = '77vh';
      autoCompleteWidth = 540
    }
    const { fqr,sjmc,pageSize, pageIndex, total, dataSate } = this.state


    const items = [
      {
        type: 'autoComplete',
        label: '事件名称',
        placeholder: '请输入 ..',
        paramName: 'eventName',
        options:sjmc,
        width:autoCompleteWidth
      },
      {
        type: 'rangePicker',
        label: '发起时间',
        paramName: 'time',
      },
      {
        type: 'autoComplete',
        label: '发起人',
        placeholder: '请输入 ..',
        paramName: 'startUserName',
        options: fqr
      },
    ];

    const columns = [
      { title: '序号', dataIndex: 'num', width: 50 },
      { title: '项目名称', dataIndex: 'projectName', key: 'platform', width: 100 },
      { title: '事件名称', dataIndex: 'eventName', key: 'name', width: 150 },

      // { title: '子事件', dataIndex: 'version', key: 'version', width: 100 },
      { title: '发起人', dataIndex: 'startUserName', key: 'upgradeNum', width: 100 },
      { title: '发起时间', dataIndex: 'operationTime', key: 'creator', width: 120, render: (text, record, index) => <span>{text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : '/'}</span> },
      // { title: '完成时间', dataIndex: 'endTime', width: 120 },
      { title: '阅读状态', dataIndex: 'haveRead', key: 'createdAt', width: 120, render: (text, record, index) => <span>{text == 1 ? '已读' : '未读'}</span> },
      { title: '抄送类型', dataIndex: 'ccType', key: 'ccType', width: 120, render: (text, record, index) => <span>{text == 1?'完成审批抄送':text == 2?'校验审批抄送':'事件完成抄送'}</span> },
      { title: '操作', key: 'operation', width: 100, render: (text, record, index) => <span><a href="javascript:;" onClick={this.onCheck.bind(this, text, record, index)}>查看</a> </span> },
    ];




    return (
      <div style={{ position: 'relative', boxSize: 'border-box', padding: 5, paddingTop: 0, paddingBottom: 0 }}>
        {/* 事件详情 */}
        {
          this.state.SubeventsInfoVisible && <SubeventsInfo
            onCancel={this.ModalCancel.bind(this, 'SubeventsInfoVisible')}
            SubeventsInfoData={this.state.SubeventsInfoData}
            visible={this.state.SubeventsInfoVisible}
          />
        }
        <Drawer
          title="审批详情"
          placement="right"
          closable={false}
          onClose={this.onClose}
          visible={this.state.visible}
          width={800}
          bodyStyle={{ height: '90%' }}
          destroyOnClose={true}
        >
          <Tab4_sub taskId={this.state.taskId} tabData={this.state.tabData} ccType={this.state.ccType} copyId={this.state.copyId} />
        </Drawer>
        <Spin spinning={this.state.spinning} size='large'>
          <Filtrate
            items={items}
            ref={ref => { this.f1 = ref }}
            submit={this.onSubmit.bind(this, 1, 10)}
            ResetForm={this.ResetForm}
          />
          <Container
            style={{ height: containerHeight, position: "relative" }}
          >
            <div style={{ position: "absolute", top: 0, left: 20, width: "93%" }}>
              <Radio checked={this.state.haveRead} onClick={this.onHaveRead}>仅显示未读信息</Radio>

            </div>

            <MyTable

              columns={columns}
              // rowSelection={rowSelection}
              scroll={{ y: height - tableHeight }}
              dataSource={PublicService.transformArrayData(dataSate, true, true, pageIndex, pageSize)}
              pagination={false}
            />
            <MyPagination
              showPage
              pageSize={pageSize}
              current={this.state.pageIndex}
              total={total}
              showSizeChanger
              showQuickJumper
              onChange={this.onChangePage.bind(this)}
              onShowSizeChange={this.onChangePage1.bind(this)}
            />




          </Container>
        </Spin>
      </div>
    );


  }
}
export default Form.create()(Tab4);


